package com.example.demo.order.config;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.listener.Listener;
import com.example.demo.util.AESUtil;
import feign.Logger;
import feign.Retryer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

@Slf4j
@Configuration
public class OrderConfig {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        configurer.setIgnoreUnresolvablePlaceholders(true);
        return configurer;
    }

    @Bean
    @Order(1)
    public AESUtil aesUtil(Environment env) {
        String property = env.getProperty("encryptKey");
        log.info("====== property:{}", property);
        return new AESUtil(property);
    }

    @LoadBalanced
    @Bean
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Bean
    ApplicationRunner applicationRunner(NacosConfigManager nacosConfigManager) {
        return args -> {
            nacosConfigManager.getConfigService().addListener("order-datasource.properties", "order", new Listener() {
                @Override
                public Executor getExecutor() {
                    return Executors.newFixedThreadPool(5);
                }

                @Override
                public void receiveConfigInfo(String s) {
                    log.info("===== ConfigChangeListener config:{}", s);
                }
            });
        };
    }


    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

    // OpenFeign 设置超时后重试策略
    @Bean
    Retryer retryer(){
        return new Retryer.Default();
    }

}
